<?php

namespace app\api\controller;

use app\traits\Help;
use app\traits\SendEmail;
use think\captcha\Captcha;
use think\Controller;
use think\facade\Cache;
use think\Request;
use think\Validate;

class Service extends Base
{
    use SendEmail, Help;

    //发送邮件
    public function sendEmailCode(Request $request)
    {
        $params   = $this->request->param();
        $validate = new Validate([
            'email' => 'require|email',
            'captcha' => 'require',
        ], [
            'name.require' => '邮箱必须'
        ]);
        if (!$validate->check($params)) {
            return $this->fail($validate->getError(), 2010);
        }
        if (!$this->checkCaptcha($params['captcha'])) {
            return $this->fail('图形验证码错误', 2011);
        }

        $code    = mt_rand(10000000, 99999999);
        $toemail = $params['email'];
        $content = '恭喜你，邮件测试成功。' . $code;
        if ($this->sendEmail($toemail, $content)) {
            Cache::set($toemail, $code, 300);
            return $this->renderJson();
        }

    }

    //图形验证码
    public function captcha()
    {
        $config  = [
            // 验证码字体大小
            'fontSize' => 22,
            // 验证码位数
            'length' => 4,
            // 关闭验证码杂点
            'useNoise' => false,
        ];
        $captcha = new Captcha($config);
        return $this->renderJson([
            'captcha' => $captcha->entry('', true)
        ]);
    }


}
